//
//  AddTabBar.m
//  CC
//
//  Created by Calvin on 4/26/15.
//  Copyright (c) 2015 Calvin. All rights reserved.
//

#import "AddTabBar.h"
#import "UIImage+Extension.h"
@interface AddTabBar()
@property (nonatomic, weak) UIButton *plusButton;
@end

@implementation AddTabBar
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        if (!iOS7) {
            self.backgroundImage =[UIImage imageWithName:@"tabbar_background"];
        }
        self.selectionIndicatorImage =[UIImage imageWithName:@"navigationbar_button_background"];
        
        [self setupPlusButton];
    }
    
    return self;
}

-(void)setupPlusButton
{
    UIButton *plusButton =[UIButton buttonWithType:UIButtonTypeCustom];
    [plusButton setBackgroundImage:[UIImage imageWithName:@"tabbar_compose_button"] forState:UIControlStateNormal];
    [plusButton setBackgroundImage:[UIImage imageWithName:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
    [plusButton setImage:[UIImage imageWithName:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
    [plusButton setImage:[UIImage imageWithName:@"tabbar_compose_icon_add_highlighted"] forState:UIControlStateHighlighted];
    [plusButton addTarget:self action:@selector(plusClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:plusButton];
    self.plusButton=plusButton;
}

-(void)plusClick
{
    if ([self.delegate respondsToSelector:@selector(tabBarDidClickedPlusButton:)]) {
        [self.delegate tabBarDidClickedPlusButton:self];
    }
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    [self setupPlusButtonFrame];
    [self setupAllTabBarButtonsFrame];
}

-(void)setupPlusButtonFrame
{
    CGRect frame =self.plusButton.frame;
    frame.size =self.plusButton.currentBackgroundImage.size;
    self.plusButton.frame = frame;
    self.plusButton.center =CGPointMake(self.frame.size.width*0.5, self.frame.size.height*0.5);
}

-(void)setupAllTabBarButtonsFrame
{
    int index = 0;
    for (UIView *tabBarButton in self.subviews) {
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")])
        {
            [self setupTabBarButtonFrame:tabBarButton atIndex:index];
        
            index++;
        }
    }
}

- (void)setupTabBarButtonFrame:(UIView *)tabBarButton atIndex:(int)index
{
    CGFloat buttonW = self.frame.size.width/(self.items.count+1);
    CGFloat buttonH = self.frame.size.height;
    CGRect frame = tabBarButton.frame;
    CGSize size = CGSizeMake(buttonW, buttonH);
    frame.size=size;
    tabBarButton.frame=frame;
    CGPoint point;
    if (index>1) {
        point.x =buttonW * (index + 1)+(buttonW/2);
    }
    else
    {
        point.x = buttonW * index+(buttonW/2);
    }
    point.y = buttonH/2;
    tabBarButton.center =point;
}
@end
